package com.ztgf.shopping.service.shop;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.shop.ShopInvoiceHeadMapper;
import com.ztgf.shopping.models.bo.shop.ShopInvoiceHeadSaveBO;
import com.ztgf.shopping.models.dto.shop.ShopInvoiceHeadDTO;
import com.ztgf.shopping.models.service.shop.IShopInvoiceHeadService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 发票抬头管理表控制器
 *
 * @author zhanghualang
 * @Date 2020-05-27 15:19:55
 */
@DubboService
public class ShopInvoiceHeadServiceImpl extends ServiceImpl<ShopInvoiceHeadMapper, ShopInvoiceHeadDTO> implements IShopInvoiceHeadService{

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(ShopInvoiceHeadSaveBO saveBO) {
        ShopInvoiceHeadDTO dto = new ShopInvoiceHeadDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public List<ShopInvoiceHeadDTO> queryPageList(Long shopId) {
        Wrapper<ShopInvoiceHeadDTO> wrapper = new EntityWrapper<>();
        if (shopId != null){
            wrapper.ge("shop_id", shopId);
        }

        wrapper.orderBy("create_time", false);//降序
        return this.selectList(wrapper);
    }

    @Override
    public boolean updateDefault(Long id) {
        ShopInvoiceHeadDTO shopInvoiceHeadDTO = this.selectById(id);
        ShopInvoiceHeadDTO newInvoiceHeadDTO = new ShopInvoiceHeadDTO();
        Wrapper<ShopInvoiceHeadDTO> wrapper = new EntityWrapper<>();
        //获取旧的dto
        ShopInvoiceHeadDTO oldShopInvoiceHeadDTO = this.selectOne(wrapper.eq("shop_id", shopInvoiceHeadDTO.getShopId()).eq("is_default", 1));
        if (oldShopInvoiceHeadDTO != null){
            ShopInvoiceHeadDTO oldDto = new ShopInvoiceHeadDTO();
            oldDto.setIsDefault(0);//改为不默认；
            oldDto.setId(oldShopInvoiceHeadDTO.getId());
            this.updateById(oldDto);
        }
        newInvoiceHeadDTO.setId(id);
        newInvoiceHeadDTO.setIsDefault(1);//改为默认
        return this.updateById(newInvoiceHeadDTO);
    }

    /**
     * 获取admin发票信息
     * @return
     */
    @Override
    public ShopInvoiceHeadDTO selectByType() {
        ShopInvoiceHeadDTO selectByType = baseMapper.selectByType();
        return selectByType;
    }
}
